package com.itheima.service;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**获取数据库返回的数据
 * @author tongchen
 * @create 2022-11-30 8:59
 */
public class BrandService {
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
    public List<Brand>selectAll(){
        //1.建立工厂

        //2.建立sqlsession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.建立mapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        List<Brand> brands = mapper.selectAll();
        //5.释放资源
        sqlSession.close();
        return brands;
    }
    public void add(Brand brand){
        //获取session对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取mapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //调用方法
        mapper.add(brand);
        //提交事务
        sqlSession.commit();
        //释放资源
        sqlSession.close();
    }
    //根据id查找
    public Brand selectById(int id){
        //1.建立工厂

        //2.建立sqlsession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.建立mapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        Brand  brand = mapper.selectById(id);
        //5.释放资源
        sqlSession.close();
        return brand;
    }
    //修改内容
    public void update(Brand brand){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.update(brand);
        sqlSession.commit();
        sqlSession.close();

    }
}
